<?php
/*--------------------------------------------------------------------
 小微OA系统 - 让工作更轻松快乐

 Copyright (c) 2013 http://www.smeoa.com All rights reserved.

 Author:  jinzhu.yin<smeoa@qq.com>

 Support: https://git.oschina.net/smeoa/xiaowei
 --------------------------------------------------------------*/

namespace Home\Controller;

class ProductController extends HomeController {
    protected $config = array('app_type' => 'folder', 'admin' => 'del,move_to,folder_manage,field_type,field_manage');

    //过滤查询字段
    function _search_filter(&$map) {
        $map['is_del'] = array('eq', '0');
        $keyword = request('keyword');
        if (!empty($keyword) && empty($map['64'])) {
            $map['name'] = array('like', "%" . $keyword . "%");
        }
    }

    public function index() {

        $plugin['date'] = true;
        $this -> assign("plugin", $plugin);

        $map = $this -> _search();
        if (method_exists($this, '_search_filter')) {
            $this -> _search_filter($map);
        }

        // $folder_list = model("SystemFolder") -> get_authed_folder();
        // if (!empty($folder_list)) {
        // $map['folder'] = array("in", $folder_list);
        // } else {
        // $map['_string'] = '1=2';
        // }

        $model = model("ProductView");

        if (!empty($model)) {
            $this -> _list($model, $map);
        }
        $this -> display();
    }

    public function edit($id) {
        $plugin['uploader'] = true;
        $plugin['date'] = true;
        $plugin['editor'] = true;
        $this -> assign("plugin", $plugin);

        $model = M("Product");
        $folder_id = $model -> where("id=$id") -> getField('folder');
        $this -> assign("auth", model("SystemFolder") -> get_folder_auth($folder_id));

        $vo = $model -> find($id);
        if (empty($vo)) {
            $this -> error("系统错误");
        }
        $this -> assign("vo", $vo);
        $field_list = model("UdfField") -> get_data_list($vo['folder'], $vo['udf_data']);

        $this -> assign("field_list", $field_list);
        $this -> display();
    }

    public function folder($fid) {
        $plugin['date'] = true;
        $this -> assign("plugin", $plugin);
        $this -> assign('auth', $this -> auth);

        $model = model("Product");
        $map = $this -> _search();
        if (method_exists($this, '_search_filter')) {
            $this -> _search_filter($map);
        }

        $map['folder'] = $fid;
        if (request('mode') == 'export') {
            $this -> _folder_export($model, $map);
        } else {
            $list = $this -> _list($model, $map);

        }

        $udf_data = $list[0]['udf_data'];
        if (!empty($udf_data)) {
            $udf_field = model("UdfField") -> get_show_field($udf_data);
        }
        $this -> assign('udf_field', $udf_field);
        $this -> assign('udf_data', $udf_data);

        $where = array();
        $where['id'] = array('eq', $fid);

        $folder_name = M("SystemFolder") -> where($where) -> getField("name");
        $this -> assign("folder_name", $folder_name);
        $this -> assign("folder", $fid);

        $this -> display();
        return;
    }

    private function _folder_export($model, $map) {
        $list = $model -> where($map) -> select();
        $i = 1;
        //导入thinkphp第三方类库
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel -> getProperties() -> setCreator("小微OA");

        $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("A$i", "编号");
        $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("B$i", "名称");
        $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("C$i", "登录人");
        $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("D$i", "登录时间");
        $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("E$i", "描述");

        $model_udf_field = model("UdfField");
        $udf_list = $model_udf_field -> get_field_list($map['folder'], 'Product');
        foreach ($udf_list as $val) {
            $k++;
            $location = get_cell_location('E', $i, $k);
            $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue($location, $val['name']);
        }
        $k = 'E';

        foreach ($list as $val) {
            $i++;
            $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("A$i", $val["doc_no"]);
            $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("B$i", $val["name"]);
            $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("C$i", $val["user_name"]);
            $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("D$i", to_date($val["create_time"], 'Y-m-d H:i:s'));
            $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("E$i", strip_tags($val["content"]));

            $field_list = $model_udf_field -> get_data_list($val['folder'], $val["udf_data"]);

            if (!empty($field_list)) {
                foreach ($field_list as $field) {
                    $k++;
                    $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("$k$i", $field['val']);
                }
            }
        }

        $objPHPExcel -> getActiveSheet() -> setTitle('产品');

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel -> setActiveSheetIndex(0);
        $file_name = "产品.xlsx";
        // Redirect output to a client’s web browser (Excel2007)
        header("Content-Type: application/force-download");
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header("Content-Disposition:attachment;filename =" . str_ireplace('+', '%20', URLEncode($file_name)));
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        //readfile($filename);
        $objWriter -> save('php://output');
        exit ;
    }

    public function add($fid) {
        $plugin['uploader'] = true;
        $plugin['date'] = true;
        $plugin['editor'] = true;
        $this -> assign("plugin", $plugin);

        $model_udf_field = model("UdfField");
        $field_list = $model_udf_field -> get_data_list($fid);

        $this -> assign("field_list", $field_list);

        $this -> assign('folder', $fid);
        $this -> display();
    }

    public function read($id) {
        $model = M("Product");
        $folder_id = $model -> where("id=$id") -> getField('folder');
        $this -> assign("auth", model("SystemFolder") -> get_folder_auth($folder_id));

        $vo = $model -> find($id);
        if (empty($vo)) {
            $this -> error("系统错误");
        }
        $this -> assign('vo', $vo);
        $field_list = model("UdfField") -> get_data_list($vo['folder'], $vo['udf_data']);

        $this -> assign("field_list", $field_list);
        $this -> display();
    }

    public function del($id) {
        $where['id'] = array('in', $id);
        $folder = M("Product") -> distinct(true) -> where($where) -> getField('folder', true);
        if (count($folder) == 1) {
            $auth = model("SystemFolder") -> get_folder_auth($folder[0]);
            if ($auth->admin == true) {
                $this -> _del($id);
            }
        } else {
            $return['info'] = "删除失败";
            $return['status'] = 0;
            $this -> ajaxReturn($return);
        }
    }

    /** 插入新新数据  **/
    protected function _insert($name = APP_NAME) {

        $model = model($name);
        if (false === $model -> create()) {
            $this -> error($model -> getError());
        }

        $model -> udf_data = model('UdfField') -> get_field_data();

        $list = $model -> add();

        if ($list !== false) {//保存成功
            //$flow_filed = model("UdfField") -> set_field($list);
            $this -> assign('jumpUrl', get_return_url());
            $this -> success('新增成功!');
        } else {
            $this -> error('新增失败!');
            //失败提示
        }
    }

    /* 更新数据  */
    protected function _update($name = APP_NAME) {
        $model = model($name);
        if (false === $model -> create()) {
            $this -> error($model -> getError());
        }
        $model -> udf_data = model('UdfField') -> get_field_data();
        $list = $model -> save();
        if (false !== $list) {
            $this -> assign('jumpUrl', get_return_url());
            $this -> success('编辑成功!');
            //成功提示
        } else {
            $this -> error('编辑失败!');
            //错误提示
        }
    }

    function folder_manage() {
        $this -> _system_folder_manage('产品分类', false);
    }

    function upload() {
        $this -> _upload();
    }

    function down($attach_id) {
        $this -> _down($attach_id);
    }

    function field_type() {
        $field_type_list = model("SystemFolder") -> get_folder_list();
        $this -> assign("list", $field_type_list);
        $this -> display();
    }

    function field_manage($row_type) {
        $this -> assign("folder_name", "产品自定义字段管理");
        $this -> _field_manage($row_type);
    }

    public function import($folder) {
        $opmode = request('opmode');
        if ($opmode == "import") {
            $import_user = array();
            $File = model('File');
            $file_driver = C('DOWNLOAD_UPLOAD_DRIVER');
            $info = $File -> upload($_FILES, C('DOWNLOAD_UPLOAD'), C('DOWNLOAD_UPLOAD_DRIVER'), C("UPLOAD_{$file_driver}_CONFIG"));
            if (!$info) {
                $this -> error('上传错误');
            } else {
                //取得成功上传的文件信息
                //$uploadList = $upload -> getUploadFileInfo();
                Vendor('Excel.PHPExcel');
                //导入thinkphp第三方类库
                $import_file = $info['uploadfile']["path"];
                $import_file = substr($import_file, 1);
                $objPHPExcel = \PHPExcel_IOFactory::load($import_file);
                //$objPHPExcel = \PHPExcel_IOFactory::load('Uploads/Download/Org/2014-12/547e87ac4b0bf.xls');
                $sheetData = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $model = M("Product");
                foreach ($sheetData[1] as $v) {
                    $udf_data_key[] = $v;
                }
                for ($i = 0; $i <= count($sheetData); $i++) {
                    foreach ($sheetData[$i] as $v) {
                        $udf[$i][] = $v;
                    }
                }
                for ($i = 2; $i <= count($udf); $i++) {
                    $data['doc_no'] = $udf[$i][0];
                    $data['user_id'] = get_user_id();
                    $data['user_name'] = get_user_name();
                    $data['create_time'] = time();
                    $data['name'] = $udf[$i][1];
                    $data['content'] = $udf[$i][2];
                    $data['folder'] = $folder;
                    for ($z = 3; $z < count($udf_data_key); $z++) {
                        $where['name'] = $udf_data_key[$z];
                        $where['controller'] = 'Product';
                        $udffield = M('UdfField') -> where($where) -> find();
                        $udf_data[$udffield['id']] = $udf[$i][$z];
                    }
                    $data['udf_data'] = json_encode($udf_data);
                    $model -> add($data);
                }
                $this -> assign('jumpUrl', get_return_url());
                $this -> success('导入成功！');
            }
        } else {
            $this -> assign('folder', $folder);
            $this -> display();
        }
    }

}
